#include "Socket.hpp"
#include <iostream>
#include <memory>
#include <sys/wait.h>
#include <functional>

using namespace SocketModule;
using namespace LogModule;


using io_service_t = std::function<void(std::shared_ptr<Socket>& sock, InetAddr& client)>;

class TcpServer
{
public:
    TcpServer(uint16_t port)
        :_port(port)
        ,_listen_sockptr(std::make_unique<TcpSocket>())
        ,_isrunning(false)
    {
        _listen_sockptr->BuildTcpSocketMethod(_port);
    }

    void Start(io_service_t callback)
    {
        _isrunning = true;
        while(_isrunning)
        {
            InetAddr client;
            auto sockptr = _listen_sockptr->Accept(&client);
            if(sockptr == nullptr)
            {
                continue;
            }
            LOG(LogLevel::DEBUG) << "accept success ... " << client.StringAddr();

            pid_t id = fork();
            if(id < 0)
            {
                LOG(LogLevel::FATAL) << "fork error ...";
                exit(FORK_ERR);
            }
            else if(id == 0)    //子进程
            {
                _listen_sockptr->Close();
                if(fork() > 0) exit(OK);
                callback(sockptr, client);
                exit(OK);
            }
            else    //父进程
            {
                sockptr->Close();
                pid_t rid = waitpid(id, nullptr, 0);
            }
        }
        _isrunning = false;
        
    }

    ~TcpServer()
    {}

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listen_sockptr;
    bool _isrunning;
};